package filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class UserLoginFilter implements Filter{

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		HttpSession session = request.getSession();
		String requestURI = request.getServletPath();
		//System.out.println(requestURI);
		String docType = requestURI.substring(requestURI.lastIndexOf(".") + 1);
	//	System.out.println(docType);
		if(requestURI.equals("/") || requestURI.trim().equals("")) {
			chain.doFilter(req, res);
		}else {
			if(session.getAttribute("user") == null && !requestURI.equals("/index.jsp") && !requestURI.equals("/index/login.action")) {
				Pattern p = Pattern.compile("jpg|gif|png|css|js");  //判断文件格式
				Matcher m = p.matcher(docType);
				if(m.matches()) {
					chain.doFilter(req, res);
				}else {
					if(!requestURI.equals("/notLogin.jsp")) {
						response.sendRedirect(request.getContextPath() + "/notLogin.jsp");
					}else {
						chain.doFilter(req, res);
					}
				}
				//System.out.println(docType);
				/*if(session.getAttribute("user") == null ) {
				if(requestURI.equals("/index.jsp")) {
					chain.doFilter(req, res);
				}else {
					if(requestURI.matches("^/\\w+.jsp$")) {
						response.sendRedirect(request.getContextPath() + "/index.jsp");
					}else {
						if(!requestURI.matches("^/\\w+login.action$")) {
							chain.doFilter(req, res);
						}else {
							response.sendRedirect(request.getContextPath() + "/index.jsp");
						}
					}
				}
				//if(requestURI.matches("^/\\w+.jsp$")) {
					//if(session.getAttribute("user") == null) {
						//response.sendRedirect(request.getContextPath() + "/index.jsp");
						//System.out.println("dddddddd");
					//}
				//}         
	*/		}else {
				chain.doFilter(req, res);
			}
		}
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
